/**
 * Copyright: Copyright (c) 2018, 2022
 * Company: 杭州叙简科技股份有限公司
 */
package cn.com.scooper.interceptor;

import cn.com.scooper.common.resp.APIRespJson;
import cn.com.scooper.common.resp.ResultCode;
import cn.com.scooper.common.util.StringUtils;
import cn.com.scooper.impl.ks.PropertyReader;
import cn.com.scooper.utils.HttpServletUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 鉴权拦截器
 *
 * @author LuLihong
 * @date 2018年4月3日
 */
public class ExtAuthInterceptor extends HandlerInterceptorAdapter {

	private final PropertyReader propertyReader;

	public ExtAuthInterceptor(PropertyReader propertyReader) {
		this.propertyReader = propertyReader;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if( isApiKeyValid(request) ){
			return true;
		}else{
			HttpServletUtils.responseJson(response, new APIRespJson(ResultCode.FAIL,"ApiKey无效"));
			return false;
		}
	}

	private boolean isApiKeyValid(HttpServletRequest request) {
		// 获取请求头中的apiKey
		String authorizationHeader = request.getHeader("Authorization");
		List<String> validApiKeys= Arrays.asList(propertyReader.getValidApiKeys().split(","));
		if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
			// 提取apiKey
			String apiKey = authorizationHeader.substring(7);
			if( !StringUtils.isEmpty(apiKey) && validApiKeys.contains(apiKey) ){
				return true;
			}
		}

		return false;
	}

}
